package jee.boot.common.interceptor;

import jee.boot.common.CommonConstant;
import jee.boot.common.properties.ProjectConfig;
import jee.boot.common.remote.RemoteEndpoint;
import jee.boot.common.utils.DateUtils;
import jee.boot.common.utils.StringUtils;
import jee.boot.entity.auth.Account;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 请求拦截器
 */
@Component
public class WebRequestInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(getClass());
    private List<String> ignoreUriList = new ArrayList<String>() {{
        add("/oauth/refresh/token");
        add("/error");
    }};
    @Autowired
    private RemoteEndpoint remoteEndpoint;
    @Autowired
    private ProjectConfig projectConfig;

    private static ThreadLocal<Long> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String path = request.getRequestURI();
        // 跳过静态资源,静态资源不会刷新超时时间
        if (StringUtils.startsWith(path, "/static/")) {
            return true;
        }
        // 跳过忽略的请求
        if (ignoreUriList.contains(path)) {
            return true;
        }
        // 服务间调用时候忽略刷新token
        String ignoreRefresh = request.getHeader("IgnoreRefresh");
        if(StringUtils.equals(CommonConstant.DATA_STATUS_ACTIVE,ignoreRefresh)){
            return true;
        }
        long time = System.currentTimeMillis();
        logger.info(request.getRequestURL() + "->请求开始时间：" + DateUtils.formatDate(new Date(time), "yyyy-MM-dd HH:mm:ss.SSS"));
        threadLocal.set(System.currentTimeMillis());
        remoteEndpoint.executePost(projectConfig.getOpenOauthServer(), "/oauth/refresh/token", new Account(), null);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long time = System.currentTimeMillis();
        long get = threadLocal.get() == null ? time : threadLocal.get();
        logger.info(request.getRequestURI() + "->请求结束时间：" + DateUtils.formatDate(new Date(time), "yyyy-MM-dd HH:mm:ss.SSS") + ";用时：" + (time - get) / 1000D + "s");
    }


}
